﻿using AutoMapper;
using HamcoWcs.Contract.ContractCommon;
using HamcoWcs.Contract.ContractMainTask;
using HamcoWcs.DAL;
using HamcoWcs.Models.Common.Enums;
using Microsoft.EntityFrameworkCore;
using Quartz;
using System;
using System.Linq;
using System.Threading.Tasks;

namespace HamcoWcs.Workers.MainTaskWokers
{
    [DisallowConcurrentExecution]
    public class MainTaskWoker : WorkerBase
    {
        public override Task Execute(IJobExecutionContext context)
        {
            var x = _wcsDbContext.MainTasks.ToList();
            x.ForEach(task => 
            {
                _baseMainTaskService.CheckCreateTimeout(task);
            });
            _wcsDbContext.SaveChanges();
            var maintasks = _wcsDbContext.MainTasks
                                         //.Where(x => x.TaskStatus != EnumMainTaskStatus.Ready.ToString())
                                         .Where(x => x.TaskStatus != EnumMainTaskStatus.Error.ToString())
                                         .Include(x => x.SubTasks)
                                         .ToList();

            if (maintasks.Count == 0) return Task.CompletedTask;

            foreach (var maintask in maintasks)
            {
                try
                {
                    switch (Enum.Parse<EnumMainTaskStatus>(maintask.TaskStatus))
                    {
                        case EnumMainTaskStatus.NewTask: _baseMainTaskService.CreatSubTask(maintask); break;
                        case EnumMainTaskStatus.Ready: _baseMainTaskService.CheckTimeout(maintask); break;
                        case EnumMainTaskStatus.OnProgress: _baseMainTaskService.ReportStart(maintask); break;
                        case EnumMainTaskStatus.Finished: _baseMainTaskService.FinishMainTask(maintask); break;
                        case EnumMainTaskStatus.Cancel: _baseMainTaskService.CancelMainTask(maintask); break;
                        case EnumMainTaskStatus.Delete: _baseMainTaskService.DeleteMainTask(maintask); break;
                            //case EnumMainTaskStatus.Error: _baseMainTaskService.DeleteMainTask(maintask); break;,
                    }
                    _wcsDbContext.SaveChanges();
                }
                catch (Exception e)
                {
                    _baseMainTaskService.SetMainTaskError(maintask);
                    _logger.AddSystemErrorLog("MainTaskWorker:" + e.Message);
                }
            }
            return Task.CompletedTask;
        }


        private readonly IBaseMainTaskService _baseMainTaskService;

        public MainTaskWoker(IMapper mapper, WcsDbContext wcsDbContext, ILoggerService logger,
                             IBaseMainTaskService baseMainTaskService)
            : base(wcsDbContext, mapper, logger)
        {
            _baseMainTaskService = baseMainTaskService;
        }
    }

}
